package net.jueb.protoServer.boot;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

import net.jueb.protoServer.handler.TcpServicePortInitializer;
import net.jueb.protoServer.handler.UdpServicePortInitializer;
import net.jueb.protoServer.portService.PortService;

/**
 * 一单对象创建,则将不可修改名称和ID
 * @author Administrator
 *
 */
public abstract class AbstractServer {
	
	protected final String serverName;
	protected final int serverId;
	protected final ConcurrentHashMap<Integer,PortService<?>> portServices;
	private TcpServicePortInitializer tcpPortInitializer;
	private UdpServicePortInitializer udpPortInitializer;
	
	public AbstractServer(int serverId,String serverName)
	{
		super();
		this.serverName = serverName;
		this.serverId = serverId;
		this.portServices=new ConcurrentHashMap<Integer,PortService<?>>();
		this.tcpPortInitializer=new TcpServicePortInitializer(portServices);
		this.udpPortInitializer=new UdpServicePortInitializer(portServices);
	}

	public final String getServerName() {
		return serverName;
	}

	public final int getServerId() {
		return serverId;
	}
	
	public final TcpServicePortInitializer getTcpPortInitializer() {
		return tcpPortInitializer;
	}
	
	/**
	 * 设置后之后再下一次启动服务器生效
	 * @param tcpPortInit
	 */
	public final void setTcpPortInitializer(TcpServicePortInitializer tcpPortInit) {
		if(tcpPortInit!=null)
		{
			this.tcpPortInitializer = tcpPortInit;
		}
	}

	public final UdpServicePortInitializer getUdpPortInitializer() {
		return udpPortInitializer;
	}
	
	/**
	 * 设置后之后再下一次启动服务器生效
	 * @param udpPortInit
	 */
	public final void setUdpPortInitializer(UdpServicePortInitializer udpPortInit) {
		if(udpPortInit!=null)
		{
			this.udpPortInitializer = udpPortInit;
		}
	}

	/**
	 * 获取服务器中的端口服务列表
	 * @return
	 */
	public final Collection<PortService<?>> getPortServices()
	{
		return this.portServices.values();
	}
	
	/**
	 * 启动服务器
	 * @return
	 */
	public abstract void startServer();
	
	/**
	 * 关闭服务器并停止所有服务
	 * @return
	 */
	public abstract void shutdown();
	
	/**
	 * 添加并运行端口服务
	 * 如果已经运行或者运行出错则返回失败
	 * @param portService
	 * @return
	 */
	public abstract boolean addPortService(PortService<?> portService);
	
	/**
	 * 停止并移出端口服务
	 * @param portServiceId
	 * @return
	 */
	public abstract boolean removePortService(int port);
}
